﻿using FrameWork.IService;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace FrameWork
{
   public class IWebSocket
   {
        private readonly WebSocket _webSocket;
        private readonly string _socketid;
       public CancellationTokenSource CancellationToken = new CancellationTokenSource();
#pragma warning restore CS1591 // 缺少对公共可见类型或成员“IWebSocket.CancellationToken”的 XML 注释

        /// <inheritdoc />
        public IWebSocket(string socketid, WebSocket webSocket)
        {
            _socketid = socketid;
            _webSocket = webSocket;
            Task.Factory.StartNew(EchoLoop);
        }
        private async Task EchoLoop()
        {
            while (_webSocket.State == WebSocketState.Open)
            {
                var buffer = new byte[4096];
                var context = new ArraySegment<byte>(buffer);
                await _webSocket.ReceiveAsync(context, CancellationToken.Token);
                if (_webSocket == null) continue;

                var services = TimHttpContext.ServiceProvider.GetServices<ISocketService>()?.ToList() ?? new List<ISocketService>();
                if (!services.Any()) continue;

                foreach (var item in services)
                {
                    var message = item.ReceiveAndSend(_socketid, context);
                    if (message == null || message.Array == null || message.Array.Length <= 0) continue;

                    await SendAsync(message);
                }
            }
        }

       public async Task SendAsync(ArraySegment<byte> message)
       {
            if (_webSocket == null || _webSocket.State != WebSocketState.Open) return;

            await _webSocket.SendAsync(message, WebSocketMessageType.Text, true, CancellationToken.Token);
        }
    }
}